<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="班组名称" prop="name">
            <el-input v-model="formItem.name" placeholder="请输入班组名称" :disabled="id !==-1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理部门" prop="orgCode">
            <TreeSelect
              v-model="formItem.orgCode"
              :multiple="false"
              :options="availableOganizations"
              placeholder="请选择管理部门"
              :disabled="id !==-1"
              @select="selcetOrg"
              @input="inputOrg"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职能" prop="functionalGroupId">
            <el-select v-model="formItem.functionalGroupId" clearable filterable remote placeholder="请选择职能" :disabled="id !==-1" @change="functionalGroupChange">
              <el-option v-for="(item) in functionalGroupList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="值班小组" prop="groupIds">
            <el-select v-model="formItem.groupIds" clearable filterable remote multiple placeholder="请选择值班组" :disabled="id !==-1" @change="teamGroupChange">
              <el-option v-for="(item) in teamGroupList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="值班规则" prop="schedulingRuleId">
            <el-select v-model="formItem.schedulingRuleId" clearable filterable remote placeholder="请选择值班规则" :disabled="id !==-1">
              <el-option v-for="(item) in schedulingRuleList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker v-model="formItem.startTime" type="date" :picker-options="pickerOptions" placeholder="选择开始时间" align="right" :disabled="id !==-1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker v-model="formItem.endTime" type="date" placeholder="选择结束时间" align="right" :disabled="id !==-1" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="小组顺序">
            <div class="board-column">
              <div class="board-column-header">拖住改变小组顺序</div>
              <draggable :list="formItem.groups" :group="{ name: 'group', pull: 'clone', put: false }" class="board-column-content">
                <div v-for="(element,index) in formItem.groups" :key="element.id" class="board-item">
                  第 {{ index + 1 }} 组 ： {{ element.name }}
                </div>
              </draggable>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

  </div>
</template>

<script>
import {
  create,
  update,
  detail
} from '@neu/dcom-ui/api/dutyArrangement'
import draggable from 'vuedraggable'
import { list } from '@neu/dcom-ui/api/functional'
import { list as getTeamGroupList } from '@neu/dcom-ui/api/teamgroup'
import { list as scRuleList } from '@neu/dcom-ui/api/schedulingrule'
import { userTree as tree } from '@neu/auth-ui/api/organization'
import TreeSelect from '@neu/biz-core/components/TreeSelect'
// 定义一个表单原始项
const formItem = {
  name: '',
  orgName: '',
  orgCode: null,
  functionalGroupId: '',
  groupIds: [],
  schedulingRuleId: null,
  startTime: null,
  endTime: null,
  groups: [],
  deleteFlag: false

}

export default {
  name: 'DutyArrangementAddForm',
  components: {
    TreeSelect,
    draggable
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 职能列表
      functionalGroupList: [],
      /** 使用部门 */
      availableOganizations: [],
      /** 值班规则列表 */
      schedulingRuleList: [],
      /** 值班组列表 */
      teamGroupList: [],
      /** 是否初始化 */
      isUpdateInit: true,
      /** 小组信息 */
      groupList: [],
      pickerOptions: { // 限制收货时间不让选择今天以前的
        disabledDate(time) {
          return time.getTime() < new Date().getTime()
        }
      },
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '班组名称不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 100) {
              callback(new Error('最多可输入100个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        orgCode: [{
          required: true,
          message: '管理部门不能为空',
          trigger: 'blur'
        }],
        groupIds: [{
          required: true,
          message: '小组不能为空',
          trigger: 'blur'
        }],
        schedulingRuleId: [{
          required: true,
          message: '规则不能为空',
          trigger: 'blur'
        }],
        functionalGroupId: [{
          required: true,
          message: '职能不能为空',
          trigger: 'blur'
        }],
        startTime: [{
          required: true,
          message: '开始时间不能为空',
          trigger: 'blur'
        }],
        endTime: [{
          required: true,
          message: '结束时间不能为空',
          trigger: 'blur'
        }]
      },
      modal: true
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    tree().then(response => {
      this.availableOganizations = [...response.data]
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.isUpdateInit = false
          const data = { ...response.data }
          this.formItem = {
            name: data.name,
            orgName: data.orgName,
            orgCode: data.orgCode,
            functionalGroupId: data.functionalGroupId,
            groupIds: [],
            schedulingRuleId: data.schedulingRuleId,
            startTime: data.startTime,
            endTime: data.endTime,
            groups: []
          }
          this.updateInit(data)
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    /** 更新初始化 */
    updateInit(sourceData) {
      const data = { ...sourceData }
      // 重新获取值班小组信息
      getTeamGroupList({ s_functionalGroupId: data.functionalGroupId }).then(res => {
        this.teamGroupList = res.data
        this.formItem.groupIds = data.groups.map(e => e.teamGroupId)
        this.formItem.groupIds.forEach(e => {
          const filterData = this.teamGroupList.filter(k => k.id === e)
          if (filterData) {
            this.formItem.groups.push(filterData[0])
          }
        })
      })

      // 获取规则信息
      scRuleList({ s_groupNumber: data.groups.length }).then(res => {
        this.schedulingRuleList = res.data
        this.formItem.schedulingRuleId = data.schedulingRuleId
      })
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            // 开始时间应该小于结束时间
            if (new Date(this.formItem.startTime).getTime() >= new Date(this.formItem.endTime).getTime()) {
              this.$message({
                showClose: true,
                message: '开始时间必须小于结束时间',
                type: 'error'
              })
              resolve(false)
            }
            const saveData = { ...this.formItem }
            // 关联组信息
            saveData.groups = this.formItem.groups.map((e, index) => {
              return {
                teamGroupId: e.id,
                teamGroupName: e.name,
                groupNumber: index + 1
              }
            })
            if (updated) {
              resolve(update(this.id, saveData))
            } else {
              resolve(create(saveData))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    /** 组织机构赋值 */
    selcetOrg(value) {
      this.formItem.orgName = value.title
    },
    /** 组织变更 */
    inputOrg(value) {
      if (this.isUpdateInit) {
        this.formItem.functionalGroupId = ''
        this.functionalGroupList = []
        // 清空掉小组列表
        this.teamGroupList = []
        this.formItem.groupIds = []
        // 清空规则列表
        this.schedulingRuleList = []
        this.formItem.schedulingRuleId = null
      }
      if (value === undefined) {
        this.formItem.orgName = ''
      } else {
        list({ 's_orgCode': value }).then(res => {
          this.functionalGroupList = res.data
        })
      }
      this.isUpdateInit = true
    },
    // 职能发生改变的时候清空列表
    functionalGroupChange(value) {
      // 清空掉小组列表
      this.teamGroupList = []
      this.formItem.groupIds = []
      // 清空规则列表
      this.schedulingRuleList = []
      this.formItem.schedulingRuleId = null
      // 获取小组信息
      if (value) {
        // 重新获取值班小组信息
        getTeamGroupList({ s_functionalGroupId: value }).then(res => {
          this.teamGroupList = res.data
        })
      }
    },
    /** 小组变化触发 */
    teamGroupChange(value) {
      // 清空规则列表
      this.schedulingRuleList = []
      this.formItem.schedulingRuleId = null
      this.formItem.groups = []

      this.formItem.groups = [...this.teamGroupList.filter(e => this.formItem.groupIds.indexOf(e.id) > -1)]
      if (value) {
        // 重新获取规则
        scRuleList({ s_groupNumber: this.formItem.groupIds.length }).then(res => {
          this.schedulingRuleList = res.data
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.board-column {
  // min-width: 300px;
  // min-height: 414px;
  height: auto;
  overflow: hidden;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .board-column-header {
    height: 40px;
    line-height: 40px;
    overflow: hidden;
    padding: 0 20px;
    text-align: center;
    color: #606266;
    border-radius: 4px 4px 0 0;
    font-size: 14px;
  }

  .board-column-content {
    height: auto;
    overflow: hidden;
    border: 5px solid transparent;
    min-height: 60px;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    align-items: center;
    font-size: 14px;

    .board-item {
      cursor: pointer;
      width: 100%;
      height: 33px;
      margin: 3px 0;
      background-color: #F0F0F0;
      text-align: left;
      line-height: 33px;
      padding: 0px 10px;
      box-sizing: border-box;
      box-shadow: 0px 1px 3px 0 rgba(0, 0, 0, 0.2);
      color: #777;
    }
  }
  .icon-margin{
    margin-left: 70%;
  }
}
</style>
